package com.cskaoyan.mall.order.controller.chain;

import com.cskaoyan.mall.common.constant.ResultCodeEnum;
import com.cskaoyan.mall.common.execption.BusinessException;
import com.cskaoyan.mall.common.result.Result;
import com.cskaoyan.mall.order.client.CartApiClient;
import com.cskaoyan.mall.order.client.ProductApiClient;
import com.cskaoyan.mall.order.client.WareApiClient;
import com.cskaoyan.mall.order.query.OrderDetailParam;
import com.cskaoyan.mall.order.query.OrderInfoParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @Author Pudding
 * @Date 2024/7/18 21:39
 * 1. 校验参数（校验库存 | 校验价格）
 */
@Component
public class ValidationHandler extends AbstractHandler{
    @Autowired
    WareApiClient wareApiClient;
    @Autowired
    ProductApiClient productApiClient;
    @Autowired
    CartApiClient cartApiClient;

    @Override
    public void handle(HandlerContext handlerContext) {

        //获取责任链上下文对象中的参数
        OrderInfoParam orderInfoParam = handlerContext.getOrderInfoParam();
        String userId = handlerContext.getUserId();


        //1. 校验
        //1.1 校验商品的库存是否足够（在这个商城中，库存服务是单独开发的）
        //1.1.1 遍历订单中商品详细信息获取商品id、商品数量
        for (OrderDetailParam orderDetailParam : orderInfoParam.getOrderDetailList()) {
            Long skuId = orderDetailParam.getSkuId();      //商品id
            Integer skuNum = orderDetailParam.getSkuNum(); //商品数量
            String skuName = orderDetailParam.getSkuName();//商品的名称

            //1.1.2 远程调用仓储服务获取库存，判断该商品是否有足够库存
            Result result = wareApiClient.hasStock(skuId, skuNum);

            if (!result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
                throw new BusinessException(skuName + " 没有库存！", 201);
                //return Result.fail().message(skuName + " 没有库存！");
            }
        }
        //1.2 校验商品价格是否产生变动
        //1.2.1 遍历订单中商品详细信息获取购物车中的商品价格、商品id
        for (OrderDetailParam orderDetailParam : orderInfoParam.getOrderDetailList()) {
            BigDecimal orderPrice = orderDetailParam.getOrderPrice();  //商品价格
            Long skuId = orderDetailParam.getSkuId();                  //商品id
            String skuName = orderDetailParam.getSkuName();            //商品的名称

            //1.2.2 远程调用商品服务获取商品实时价格（对应的服务需要对外暴露接口）
            BigDecimal currentPrice = productApiClient.getSkuPrice(skuId);

            //1.2.3 判断价格是否变动
            //如果不一致，就更新购物车中商品的价格（远程调用购物车中更新用户购物车中商品价格 + 购物车服务中再调用商品服务接口获取最新价格）
            if (!orderPrice.equals(currentPrice)) {

                cartApiClient.refreshCartPrice(userId, skuId);
                //返回价格发生变动，让用户重新提交订单
                throw new BusinessException(skuName + " 的价格发生变动！", 201);
                //return Result.fail().message(skuName + " 的价格发生变动！");
            }
        }

        if (nextHandler != null){
            nextHandler.handle(handlerContext);
        }
    }
}
